﻿package makeeasier.air.file {
	
	import flash.events.*;
	import flash.filesystem.*;
	import flash.utils.*;
	
	public class BatchCopier extends EventDispatcher {
		
		private var fileList:Vector.<File>;
		private var _destination:File;
		private var _current:Number;
		private var _currentFileProgress:Number;
		private var _totalFileProgress:Number;
		private var _completedSize:Number;
		private var _totalSize:Number;
		
		
		public function BatchCopier(){
			fileList = new Vector.<File>();
			_current = -1;
		}
		
		public function addItem(item:File):void{
			fileList.push(item);
		}
		
		public function removeItem(item:File):void{
			delete fileList[fileList.indexOf(item)];
			
		}
		
		public function start():Boolean{
			if(!_destination || !fileList.length){
				return false;
			}
			_current = -1;
			_totalSize = 0;
			_completedSize = 0;
			calculateTotal();
			fileWorker();
			return true;
		}
		
		public function calculateTotal():void{
			for(var i=0; i<fileList.length; i++){
				var f:File = fileList[i];
				if(f.exists){
					_totalSize += f.size;
				}
			}
		}
		
		public function fileWorker():void{
			_current++;
			var worker:FileCopier = new FileCopier();
			worker.source = fileList[_current].nativePath;
			worker.destination = _destination.nativePath + "/" + fileList[_current].name
			worker.addEventListener("progress", fileWorkerProgress);
			worker.addEventListener("complete", isFinished);
			worker.start();
			dispatchEvent(new Event("nextfile"));
		}
		
		public function isFinished(e:Event):void{
			if(_current == fileList.length-1){
				dispatchEvent(new Event("complete"));
			} else {
				_completedSize += fileList[_current].size;
				fileWorker();
			}
		}
		
		public function fileWorkerProgress(e:Event):void{
			_currentFileProgress = e.target.bytesLoaded / e.target.bytesTotal;
			_totalFileProgress = (_completedSize+e.target.bytesLoaded) / _totalSize;
			dispatchEvent(new Event("progress"));
		}
		
		public function get destination():String{
			return _destination.nativePath;
		}
		
		public function set destination(s:String):void{
			_destination = new File(s);
		}
		
		public function get currentProgress():Number{
			return _currentFileProgress;
		}
		
		public function get totalProgress():Number{
			return _totalFileProgress;
		}
		
		public function get currentFile():File{
			return fileList[_current];
		}
		
	}
	
	
}